package com.liqi.frame.comm.controller.manager;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liqi.frame.comm.Constants;
import com.liqi.frame.comm.dto.HttpResult;
import com.liqi.frame.comm.dto.LayuiTableData;
import com.liqi.frame.comm.dto.PermissionTreeDto;
import com.liqi.frame.comm.enums.ResultEnum;
import com.liqi.frame.comm.po.Group;
import com.liqi.frame.comm.po.Permission;
import com.liqi.frame.comm.po.User;
import com.liqi.frame.comm.service.GroupService;
import com.liqi.frame.comm.service.PermissionService;
import com.liqi.frame.comm.service.UserService;
import com.liqi.frame.comm.token.TokenUtil;
import com.liqi.frame.comm.util.IdUtil;
import com.liqi.frame.comm.util.PermissionUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by liqi on 2017/11/30.
 * liqiwork@qq.com
 */
@Controller
@RequestMapping("/userManager/ajax")
public class UserManagerAjaxController {

    /**
     * @param theme 换肤主题（json类型存储）
     *
     */
    @RequestMapping({"saveSkin"})
    @ResponseBody
    public HttpResult saveSkin(@RequestBody Map params) {
        String theme = params.get("theme")+"";

        String userId = TokenUtil.getUserId();
        int resultStatus1;
        resultStatus1 = userService.updateUser(userId, null, null, 1, null, null, null, null, null, null, null, theme,null, null);

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        if(resultStatus1 == 0) {
            result.setCode(ResultEnum.FAILURE.getCode());
        }
        return result;
    }


    /**
     * 取用户列表(分页)
     * @param page
     * @param limit
     * @param fullname
     * @return
     */
//    @RequiresPermissions(value = {"userManager:getUserManagerList", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getUserManagerList"})
    @ResponseBody
    public LayuiTableData getUserManagerList(@RequestBody Map params) {
        Integer page = (Integer)params.get("page");
        Integer limit = (Integer)params.get("limit");
        String parentGroupId = params.get("parentGroupId")+"";
        String fullname = params.get("fullname")+"";

        LayuiTableData result = new LayuiTableData(ResultEnum.SUCCESS);
        User currentUser = TokenUtil.getToken();
        if (StrUtil.isEmpty(parentGroupId)) {
            parentGroupId = currentUser.getGroupId();
        }
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(parentGroupId);
        Long total = 0L;
        List listData = new ArrayList();
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            PageHelper.startPage(page, limit);
            List list = userService.selectList(fullname, groupIds);
            if (list!=null && list.size()>0) {
                PageInfo pageInfo = new PageInfo(list);
//                List list1 = userService.selectList(fullname, groupIds);
//                result.setCount(list1.size());
                total = pageInfo.getTotal();
                listData = pageInfo.getList();
            }
        }
        return LayuiTableData.success(listData, total);
    }

//    @RequiresPermissions(value = {"userManager:getUserById", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getUserById"})
    @ResponseBody
    public HttpResult getUserById(@RequestBody Map params) {
        String id = params.get("id")+"";

        Map map = new HashMap();
        User user = this.userService.getUserById(id);
//        map.put("unitFile",unitFileService.selectById_common(user.getAvatar()));
        map.put("user",user);
        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        result.setData(map);
        return result;
    }

    @RequiresPermissions(value = {"userManager:save", "userManager:saveUser",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"saveUser"})
    @ResponseBody
    public HttpResult saveUser(@RequestBody Map params) {
        String fileJson = params.get("fileJson")+"";
        String id = params.get("id")+"";
        String pswd = params.get("pswd")+"";
        String username = params.get("username")+"";
        String fullname = params.get("fullname")+"";
        String phone = params.get("phone")+"";
        String email = params.get("email")+"";
        String comment = params.get("comment")+"";
        Object orderIdObject = params.get("orderId");
        Float orderId = new Float(0);
        if (Objects.isNull(orderIdObject)) {
            orderId = Float.parseFloat(params.get("orderId") + "");
        }
        String groupId = params.get("groupId")+"";
        String groupName = params.get("groupName")+"";
        String theme = params.get("theme")+"";

//        String realPath = session.getServletContext().getRealPath("/");
        int resultStatus1;
        if (id != null && !"".equals(id)) {
//            User user = userService.getUserById(id);
//            unitFileService.deleteFile(user.getAvatar(),TokenUtil.getUserId());
//            List<UnitFile> list = unitFileService.uploadFiles(fileJson,realPath,null,null,null,TokenUtil.getUserId());
//            if (list!=null) {
//                resultStatus1 = this.userService.updateUser(id, username, (String)null, 1, fullname, phone, email, comment, orderId, groupId, groupName, theme,list.get(0).getId());
//            } else {
                resultStatus1 = this.userService.updateUser(id, username, (String)null, 1, fullname, phone, email, comment, orderId, groupId, groupName, theme,null, null);
//            }

        } else {
//            List<UnitFile> list = unitFileService.uploadFiles(fileJson,realPath,null,null,null,TokenUtil.getUserId());
//            if (list!=null) {
//                resultStatus1 = this.userService.insertUser(IdUtil.getId() + "", username, pswd, 1, fullname, phone, email, comment, orderId, groupId, groupName,theme,list.get(0).getId());
//            } else {
                resultStatus1 = this.userService.insertUser(IdUtil.getId() + "", username, pswd, 1, fullname, phone, email, comment, orderId, groupId, groupName,theme,null, null);
//            }
        }
        if (resultStatus1 > 0) {
            return HttpResult.success("保存成功！");
        } else {
            return HttpResult.success("保存失败！");
        }
    }

    @RequiresPermissions(value = {"userManager:delete",
                                  "userManager:deleteUser",
            Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"deleteUser"})
    @ResponseBody
    public HttpResult deleteUser(@RequestBody Map params) {
        String id = params.get("id")+"";

        HttpResult result = new HttpResult(ResultEnum.SUCCESS);
        User user = userService.getUserById(id);
        if (user!=null && PermissionUtil.judgeAdministrator(user.getUsername())) {
            return HttpResult.failure("不允许删除管理员!");
        } else {
            int resultStatus = userService.deleteUser(id);
            if (resultStatus > 0) {
                return HttpResult.success("删除成功！");
            } else {
                return HttpResult.failure("删除失败！");
            }
        }
    }

    /**
     * @param userName 账号
     * 通过username查询user表
     */
//    @RequiresPermissions(value = {"userManager:getUserByUserName", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getUserByUserName"})
    @ResponseBody
    public HttpResult getUserByUserName(@RequestBody Map params) {
        String userName = params.get("userName")+"";

        User user = this.userService.getByUsername(userName);
        return HttpResult.success(user);
    }

    /**
     * @param id 用户id
     * @param userName 账号
     * 在编辑时通过username查询user表，并排除当前的username的user
     */
//    @RequiresPermissions(value = {"userManager:getUserByUserNameOutCurrent", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getUserByUserNameOutCurrent"})
    @ResponseBody
    public HttpResult getUserByUserNameOutCurrent(@RequestBody Map params) {
        String id = params.get("id")+"";
        String userName = params.get("userName")+"";

        User user = this.userService.getByUsername(userName);
        if(user!=null){
            if (user.getId().equals(id)){
                return HttpResult.success(null);
            }else {
                return HttpResult.success(user);
            }
        }else{
            return HttpResult.success(null);
        }
    }

    /**
     * @param id 用户id
     *
     */
    @RequiresPermissions(value = {"userManager:getPermissionListByUserId", Constants.OPERATION_PASSKEY}, logical = Logical.OR)
    @RequestMapping({"getPermissionListByUserId"})
    @ResponseBody
    public HttpResult getPermissionListByUserId(@RequestBody Map params) {
        String id = params.get("id")+"";

        List<Permission> list = permissionService.getPermissionListByUserId(id);
        List<Permission> menuList = new ArrayList<>();
        List<Permission> operationList = new ArrayList<>();
        //操作菜单分离
        for(int i=0;i<list.size();i++){
            if (list.get(i).getPermissionType().equals("menu")){
                menuList.add(list.get(i));
            }
            if (list.get(i).getPermissionType().equals("operation")){
                operationList.add(list.get(i));
            }
        }
        //菜单组装为树结构
        PermissionTreeDto menuTree = new PermissionTreeDto();
        //一级、二级菜单分离菜单
        List<Permission> menuLevel_1_List = new ArrayList<>();
        List<Permission> menuLevel_2_List = new ArrayList<>();
        for(int i=0;i<menuList.size();i++){
            if(menuList.get(i).getLevel()==1){
                menuLevel_1_List.add(menuList.get(i));
            }
            if(menuList.get(i).getLevel()==2){
                menuLevel_2_List.add(menuList.get(i));
            }
        }
        // 菜单的树结构  二级菜单放入对应的父级(一级)菜单中并组装为PermissionTree类型
        List<PermissionTreeDto> menuPtList = new ArrayList<>();
        for(int i=0;i<menuLevel_1_List.size();i++){
            PermissionTreeDto pt_level_1 = new PermissionTreeDto();
            pt_level_1.setName(menuLevel_1_List.get(i).getPermissionName());
            pt_level_1.setValue(menuLevel_1_List.get(i).getPermissionKey());
            List<PermissionTreeDto> childList = new ArrayList<>();
            for(int j=0;j<menuLevel_2_List.size();j++){
                if(menuLevel_2_List.get(j).getParentId().equals(menuLevel_1_List.get(i).getId())){
                    PermissionTreeDto childPt = new PermissionTreeDto();
                    childPt.setName(menuLevel_2_List.get(j).getPermissionName());
                    childPt.setValue(menuLevel_2_List.get(j).getPermissionKey());
                    childList.add(childPt);
                }
            }
            pt_level_1.setChildren(childList);
            menuPtList.add(pt_level_1);
        }
        //操作的树结构
        List<PermissionTreeDto> perPtList = new ArrayList<>();
        for(int i=0;i<operationList.size();i++){
            PermissionTreeDto perPt = new PermissionTreeDto();
            perPt.setName(operationList.get(i).getPermissionName());
            perPt.setValue(operationList.get(i).getPermissionKey());
            perPtList.add(perPt);
        }
        Map map = new HashMap();
        map.put("menu",menuPtList);
        map.put("permission",perPtList);
        return HttpResult.success(map);
    }

    @RequestMapping({"modifyPassword"})
    @ResponseBody
    public HttpResult modifyPassword(@RequestBody Map params) {
        String oldPassword = params.get("oldPassword")+"";
        String newPassword = params.get("newPassword")+"";

        String username = TokenUtil.getUsername();
        int resultCount = userService.modifyPassword(username, oldPassword, newPassword);
        if (resultCount>0) {
            return HttpResult.success("修改成功！");
        } else {
            return HttpResult.failure("修改失败：旧密码错误。");
        }
    }


    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
//    @Autowired
//    private UnitFileService unitFileService;
    @Autowired
    private GroupService groupService;
}
